package com.yeebo.admin.service;

import com.github.pagehelper.Page;
import com.yeebo.admin.domain.SysRoleDomain;
import com.yeebo.enums.ResultCode;
import com.yeebo.exception.ServiceException;
import com.yeebo.model.admin.SysRole;
import com.yeebo.model.admin.SysRoleResource;
import com.yeebo.rpc.admin.SysRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleDomain sysRoleDomain;

    @Override
    public Page<SysRole> loadSysRoleManageList(Integer pageNo, Integer pageSize, String filterRoleName) {
        return sysRoleDomain.loadSysRoleList(pageNo, pageSize, filterRoleName);
    }

    @Override
    public void addSysRole(String roleCode, String roleName, String roleDesc) {
        SysRole checkExistRole = sysRoleDomain.getSysRoleByCode(roleCode);
        if (checkExistRole != null) {
            throw new ServiceException(ResultCode.SYS_ROLE_CODE_REPEAT);
        }
        sysRoleDomain.addSysRole(roleCode, roleName, roleDesc);
    }

    @Override
    public void updateSysRole(Long roleId, String roleName, String roleDesc) {
        SysRole existRole = sysRoleDomain.getSysRoleById(roleId);
        existRole.setRoleName(roleName);
        existRole.setRoleDesc(roleDesc);
        sysRoleDomain.updateSysRole(existRole);
    }

    @Override
    public void deleteSysRole(Long roleId) {
        SysRole existRole = sysRoleDomain.getSysRoleById(roleId);
        if (existRole.getRoleCode().equalsIgnoreCase("SUPER_ADMIN")
            || existRole.getRoleCode().equalsIgnoreCase("NORMAL_ADMIN")) {
            throw new ServiceException(ResultCode.CAN_NOT_DELETE_SUPER_ROLE);
        }
        existRole.setValid(false);
        sysRoleDomain.updateSysRole(existRole);
    }

    @Override
    public SysRole getSysRoleById(Long roleId) {
        return sysRoleDomain.getSysRoleById(roleId);
    }

    @Override
    public Map<String, Object> loadSysResourcesVOByRoleId(Long roleId) {
        Map<String, Object> body = new HashMap<>();
        body.put("resourcesTreeList", sysRoleDomain.loadSysResourcesTree());
        body.put("roleCurrentHaveResources", sysRoleDomain.loadCurrentHaveResourcesByRoleId(roleId));
        return body;
    }

    @Override
    public void assignResourcesToRole(Long roleId, List<Long> resourceIdList) {
        List<SysRoleResource> sysRoleResources = new LinkedList<>();
        for (Long resourceId : resourceIdList) {
            SysRoleResource entity = new SysRoleResource();
            entity.setRoleId(roleId);
            entity.setResourceId(resourceId);
            sysRoleResources.add(entity);
        }
        sysRoleDomain.assignResourcesToRole(roleId, sysRoleResources);
    }

}
